export default {
  namespaced:true,
  state:()=>({
    car:JSON.parse(uni.getStorageSync('car') || '[]')
    // car: JSON.parse(uni.getStorageSync('car')) || []
    // car:[]
  }),
  mutations:{
    addCar(state,data){
    let findResult = state.car.find(val=> val.goods_id==data.goods_id)
    if(findResult){
      findResult.goods_count++
    }else{
      state.car.push(data)
    }
    this.commit('car/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('car',JSON.stringify(state.car))
    },
    updataGoodsState(state,data) {
      let findResult = state.car.find(val=> val.goods_id==data.goods_id)
      findResult.goods_state = data.goods_state
       this.commit('car/saveToStorage')
    },
    updataGoodsCount(state,data) {
      let findResult = state.car.find(val=> val.goods_id==data.goods_id)
      findResult.goods_count = data.goods_count
       this.commit('car/saveToStorage')
    },
    removeGoodsById(state,goods_id) {
      state.car = state.car.filter(val=>val.goods_id !== goods_id)
       this.commit('car/saveToStorage')
    },
    // 更新所有商品的勾选状态
    updateAllGoodsState(state, newState) {
      // 循环更新购物车中每件商品的勾选状态
      state.car.forEach(x => x.goods_state = newState)
      // 持久化存储到本地
      this.commit('car/saveToStorage')
    }
  },
  getters:{
    total(state) {
      let sum = 0
      state.car.forEach(val=>sum+=(val.goods_count*1))
      return sum
    },
    // 勾选的商品的总数量
    checkedCount(state) {
      // 先使用 filter 方法，从购物车中过滤器已勾选的商品
      // 再使用 reduce 方法，将已勾选的商品总数量进行累加
      // reduce() 的返回值就是已勾选的商品的总数量
      return state.car.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count*1, 0)
    },
    checkedAllPrice(state) {
      return state.car.filter(val=>val.goods_state)
                      .reduce((allPrice,item)=>item.goods_count*item.goods_price*1,0).toFixed()
    }
  }
}